package com.frogs.ucenter.v1.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.frogs.framework.util.PageList;
import com.frogs.system.util.UserIntegralRecordEnum;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.dao.UserAttentionInfoDao;
import com.frogs.ucenter.dao.UserIntegralBalanceDao;
import com.frogs.ucenter.dao.UserIntegralRecordBackDao;
import com.frogs.ucenter.entity.UserIntegralBalance;
import com.frogs.ucenter.entity.UserIntegralRecord;
import com.frogs.ucenter.entity.UserIntegralRecordBack;
import com.frogs.ucenter.entity.ext.UserAttentionInfoExt;
import com.frogs.ucenter.entity.ext.UserIntegralBalanceExt;
import com.frogs.ucenter.v1.request.AttentionIntegralListRequest;
import com.frogs.ucenter.v1.request.UserIntegralBalanceAddByConsumeRequest;
import com.frogs.ucenter.v1.request.UserIntegralBalanceAddRequest;
import com.frogs.ucenter.v1.request.UserIntegralBalanceBackByConsumeRequest;
import com.frogs.ucenter.v1.request.UserIntegralBalanceShowRequest;
import com.frogs.ucenter.v1.request.UserIntegralRecordListRequest;
import com.frogs.ucenter.v1.response.AttentionIntegralListResponse;
import com.frogs.ucenter.v1.response.DefaultResponse;
import com.frogs.ucenter.v1.response.PageListResponse;
import com.frogs.ucenter.v1.response.ShowResponse;
import com.frogs.ucenter.v1.service.UserIntegralBalanceService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"userIntegralBalanceService")
public class UserIntegralBalanceServiceImpl extends UserRechargeStrategyBaseServiceImpl implements UserIntegralBalanceService {

	private Logger log = LoggerFactory.getLogger(UserIntegralBalanceServiceImpl.class);
	
	@Resource
	private UserIntegralBalanceDao userIntegralBalanceDao;
	@Resource
	private UserIntegralRecordBackDao userIntegralRecordBackDao;
	@Resource
	private UserAttentionInfoDao userAttentionInfoDao;
	
	@Override
	public Response showUserIntegralBalance(Request request) throws Exception {
		UserIntegralBalanceShowRequest showRequest = (UserIntegralBalanceShowRequest) request;
		ShowResponse<UserIntegralBalance> showResponse = new ShowResponse<UserIntegralBalance>();
		try {
			int userId = showRequest.getUserId();
			
			UserIntegralBalance integral = userIntegralBalanceDao.selectById(userId);
			if (integral == null) {
				integral = new UserIntegralBalance();
				integral.setIntegralUsable(0);
				integral.setIntegralUsed(0); 
				integral.setId(userId); 
				integral.setUpdateTime(new Date()); 
			}
			showResponse.setInfo(integral);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return showResponse;
	}

	@Override
	public Response addByConsumeUserIntegralBalance(Request request) throws Exception {
		UserIntegralBalanceAddByConsumeRequest addRequest = (UserIntegralBalanceAddByConsumeRequest) request;
		DefaultResponse response = new DefaultResponse();
		try {
			int userId = addRequest.getUserId();//用户ID
			int type = addRequest.getType();//积分来源,枚举UserIntegralRecordEnum
			BigDecimal rechargeMoney = addRequest.getConsumeMoney();//消费金额
			String expandCode = addRequest.getExpandCode();//渠道
			String remark = "订单号："+addRequest.getRemark();//来源明细说明
			int applicablePlatformId = addRequest.getApplicablePlatformId();//平台
			String orderId = addRequest.getOrderId();//订单id
			givePointByConsume(userId ,rechargeMoney , type , expandCode , remark, applicablePlatformId, orderId);
			response.setTip("添加积分成功");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/* 
	 *消费获取的积分回滚
	 */
	@Override
	public Response backByConsumeUserIntegralBalance(Request request) throws Exception {
		UserIntegralBalanceBackByConsumeRequest backRequest = (UserIntegralBalanceBackByConsumeRequest) request;
		DefaultResponse response = new DefaultResponse();
		try {
			int userId = backRequest.getUserId();//用户ID
			String orderId = backRequest.getOrderId();//订单id
			//1、查看积分记录表是否存在该条记录，不存在则直接返回
			//2、查看回滚记录表user_integral_record_back是否存在该条记录，存在则直接返回
			//3、登记回滚记录表，添加积分记录表，修改用户积分余额
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqUserId", userId);
			params.put("eqOrderId", orderId);
			params.put("eqType", UserIntegralRecordEnum.ORDER_EXCHANGE.getId());
			PageList<UserIntegralRecord> list = userIntegralRecordDao.selectByMap(params, false);
			if(list.size()>0){
				params = new HashMap<String, Object>();
				params.put("eqOrderId", orderId);
				PageList<UserIntegralRecordBack> backList = userIntegralRecordBackDao.selectByMap(params, false);
				if(backList.size()>0){
					response.setTip("该订单已经回滚过，无需再回滚");
				}else{
					UserIntegralRecordBack userIntegralRecordBack = new UserIntegralRecordBack();
					userIntegralRecordBack.setOrderId(orderId);
					userIntegralRecordBackDao.insert(userIntegralRecordBack);
					UserIntegralRecord oldUserIntegralRecord = list.get(0);
					super.givePoint(userId ,0-oldUserIntegralRecord.getIntegralNum() ,UserIntegralRecordEnum.ORDER_BACK_DONATE.getId() 
							, oldUserIntegralRecord.getExpandCode(), "取消订单系统自动回退积分", oldUserIntegralRecord.getApplicablePlatformId(), orderId);
					response.setTip("积分回滚成功");
				}
			}else{
				response.setTip("不存在该订单，无需回滚");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}

	@Override
	public Response addUserIntegralBalance(Request request) throws Exception {
		UserIntegralBalanceAddRequest addRequest = (UserIntegralBalanceAddRequest) request;
		DefaultResponse response = new DefaultResponse();
		try {
			int userId = addRequest.getUserId();//用户ID
			int type = addRequest.getType();//积分来源
			int point = addRequest.getPoint();//消费金额
			String expandCode = addRequest.getExpandCode();//渠道
			String remark = addRequest.getRemark();//说明
			String orderId = "";//只有订单消费才需要传送订单号，此处不用传
			int applicablePlatformId = addRequest.getApplicablePlatformId();//平台
			super.givePoint(userId ,point , type ,expandCode , remark, applicablePlatformId, orderId);
			response.setTip("添加积分成功");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}

	@Override
	public Response getUserIntegralRecordList(Request request) throws Exception {
		UserIntegralRecordListRequest userIntegralRecordListRequest = (UserIntegralRecordListRequest)request;
		PageListResponse<UserIntegralRecord> response = new PageListResponse<UserIntegralRecord>();
		try {
			int userId = userIntegralRecordListRequest.getUserId();//用户ID
			//查询列表不用增加渠道和平台的查询条件
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqUserId", userId);
			params.put("orderByClause", "integral_time desc");
    		int pageNo = userIntegralRecordListRequest.getPageNum();
    		int pageSize = userIntegralRecordListRequest.getNumPerPage();
			PageList<UserIntegralRecord> list = super.userIntegralRecordDao.selectByMap(params, pageNo, pageSize);
			response.setList(list);
			response.setPageTurn(list.getPageTurn());
			response.setTip("查询积分列表成功");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}

	@Override
	public Response getAttentionIntegralList(Request request) throws Exception {
		PageListResponse<UserIntegralBalanceExt> response = new PageListResponse<UserIntegralBalanceExt>();
		PageList<UserIntegralBalanceExt> integralList = new PageList<UserIntegralBalanceExt>();
		try {
    		AttentionIntegralListRequest listRequest = (AttentionIntegralListRequest)request;
    		Map<String,Object> params = new HashMap<String,Object>();
    		if(listRequest.getUserId() > 0)
    			params.put("eqFollowUserId", listRequest.getUserId());
    		params.put("eqStatus",listRequest.getStatus() );
    		integralList = userIntegralBalanceDao.selectExtByMap(params, listRequest.getPageNum(), listRequest.getPageSize());
    		response.setList(integralList);
    		response.setPageTurn(integralList.getPageTurn());
	    	response.setTip("查询成功");
	    } catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}

}